package com.weibo.sina;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.TimerTask;

import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.androidexamples.OAuthConstant;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class Authorize extends Activity {

	static final String TAG = "Authorize";
	static final String FACEACTIVITY = "app://TimeLineActivity";
	public static boolean ISAUTHORED = false;
	private boolean mIsNetConnect = true;
	RequestToken requestToken;
	private AnimationDrawable mFrameAnimation;
	private Handler mHandle;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);

		// ImageView img = (ImageView)findViewById(R.id.logo_bo);
		// img.setBackgroundResource(R.drawable.bo);
		// mFrameAnimation = (AnimationDrawable) img.getBackground();
		// Log.e(TAG, " frameAnimation.start()" );
		// (new Timer(false)).schedule(new AnimationTimer(mFrameAnimation),
		// 100);

	}

	@Override
	protected void onResume() {
		Log.e(TAG, "onResume");
		if (!checkNetworkInfo()) {
			mIsNetConnect = false;
			showDialog(0);
		} else {
			Thread initThread = new Thread() {

				@Override
				public void run() {
					Log.e(TAG, "mIsNetConnect　＝　" + mIsNetConnect + " ISAUTHORED=" + ISAUTHORED);
					if (mIsNetConnect && ISAUTHORED) {
						startActivity(new Intent(Authorize.this, TimeLineView.class));
						finish();
					} else {
						try {
							OAuthConstant.initData();
							Weibo weibo = OAuthConstant.getInstance().getWeibo();
							requestToken = weibo.getOAuthRequestToken(FACEACTIVITY);
							Log.e(TAG, "init requestToken ");
							OAuthConstant.getInstance().setRequestToken(requestToken);
						} catch (WeiboException e) {
							e.printStackTrace();
							Log.e(TAG, "WeiboException status code =  " + e.getStatusCode());
						}
						Button beginOuathBtn = (Button) findViewById(R.id.getAccessToken);
						beginOuathBtn.setVisibility(View.VISIBLE);
						beginOuathBtn.setOnClickListener(new Button.OnClickListener() {

							public void onClick(View v) {
								Log.e(TAG, requestToken.getAuthenticationURL());
								Uri uri = Uri.parse(requestToken.getAuthenticationURL() + "&from=xweibo");
								Log.e(TAG, uri.toString());
								startActivity(new Intent(Intent.ACTION_VIEW, uri));
//								Intent intent = new Intent(Authorize.this,
//										 SimpleWebView.class);
//								intent.putExtra("uri", uri.toString());
//								startActivity(intent);
//								try {
//									File file =  new File("/sdcard/log.log");
//									FileOutputStream fos = new FileOutputStream(file);
//									InputStream is;
//
//									is = new URL(uri.toString()).openStream();
//									int data = is.read();
//									while (data != -1) {
//										fos.write(data);
//										data = is.read();
//										;
//									}
//									fos.close();
//									is.close();
//
//								} catch (MalformedURLException e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								} catch (IOException e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								}

								finish();
								// startActivity(new Intent(Authorize.this,
								// MapMode.class));
							}
						});

					}
					// SharedPreferences user = getSharedPreferences("oauth",
					// 0);
					// String oauth_verifier = user.getString("oauth_verifier",
					// null);

					/*
					 * try { OAuthConstant.initData(); Weibo weibo =
					 * OAuthConstant.getInstance().getWeibo(); requestToken =
					 * weibo.getOAuthRequestToken(FACEACTIVITY); Log.e(TAG,
					 * "init requestToken ");
					 * OAuthConstant.getInstance().setRequestToken
					 * (requestToken); // if (oauth_verifier != null) { //
					 * AccessToken accessToken =
					 * requestToken.getAccessToken(oauth_verifier); //
					 * OAuthConstant.getInstance().setAccessToken(accessToken);
					 * // } Log.e(TAG, "accessToken get success "); } catch
					 * (WeiboException e) {
					 * 
					 * e.printStackTrace(); Log.e(TAG,
					 * "WeiboException status code =  " + e.getStatusCode());
					 * beginOuathBtn.setVisibility(View.VISIBLE); ISAUTHORED =
					 * false; }
					 */

					super.run();
				}

			};
			mHandle = new Handler();
			mHandle.postDelayed(initThread, 1000);

		}
		super.onResume();

	}

	private static class AnimationTimer extends TimerTask {
		AnimationDrawable animation;

		public AnimationTimer(AnimationDrawable animation) {
			this.animation = animation;
		}

		@Override
		public void run() {
			animation.start();
			this.cancel();
		}

	}

	private boolean checkNetworkInfo() {
		ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		// 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
		if (mobile == State.CONNECTED || mobile == State.CONNECTING)
			return true;
		if (wifi == State.CONNECTED || wifi == State.CONNECTING)
			return true;
		return false;
		// 进入无线网络配置界面
		// startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
		// //进入手机中的wifi网络设置界面
	}

	protected Dialog onCreateDialog(int id, Bundle args) {
		return new AlertDialog.Builder(Authorize.this).setTitle(getString(R.string.net_not_connect))
				.setPositiveButton(R.string.set_net, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
					}
				}).setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						finish();
					}
				}).create();
	}

}
